﻿IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[medianamik_NodeRevision]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[medianamik_NodeRevision](
	[NodeRevisionId] [uniqueidentifier] NOT NULL,
	[NodeId] [uniqueidentifier] NOT NULL,
	[CreatedOn] [datetime] NOT NULL,
	[PublishedOn] [datetime] NULL,
	[Data] [xml] NOT NULL,
 CONSTRAINT [PK_medianamik_NodeRevision] PRIMARY KEY CLUSTERED 
(
	[NodeRevisionId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [I_NodeRevision_CreatedOn_NodeId] ON [dbo].[medianamik_NodeRevision] 
(
	[NodeId] ASC,
	[CreatedOn] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

ALTER TABLE [dbo].[medianamik_NodeRevision]  WITH CHECK ADD  CONSTRAINT [FK_NodeRevision__Node] FOREIGN KEY([NodeId])
REFERENCES [dbo].[medianamik_Node] ([NodeId])
ON DELETE CASCADE

ALTER TABLE [dbo].[medianamik_NodeRevision] CHECK CONSTRAINT [FK_NodeRevision__Node]

ALTER TABLE [dbo].[medianamik_NodeRevision] ADD  CONSTRAINT [DF_medianamik_NodeRevision_Published]  DEFAULT ((0)) FOR [PublishedOn]
END



IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_medianamik_NodeRevision]'))
BEGIN
EXEC('CREATE VIEW [dbo].[vw_medianamik_NodeRevision]
AS
SELECT	nr.*
FROM	medianamik_NodeRevision nr
		left join dbo.medianamik_NodeRevision latest  on nr.NodeId = latest.NodeId and nr.CreatedOn < latest.CreatedOn
WHERE	nr.PublishedOn is null 
and		latest.NodeId is null')
END